home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / python2.4 / distutils / util.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2007-04-29  |  14.7 KB  |  439 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.4)
  3.  
  4. """distutils.util
  5.  
  6. Miscellaneous utility functions -- anything that doesn't fit into
  7. one of the other *util.py modules.
  8. """
  9. __revision__ = '$Id: util.py 52231 2006-10-08 17:41:25Z ronald.oussoren $'
  10. import sys
  11. import os
  12. import string
  13. import re
  14. from distutils.errors import DistutilsPlatformError
  15. from distutils.dep_util import newer
  16. from distutils.spawn import spawn
  17. from distutils import log
  18.  
  19. def get_platform():
  20.     """Return a string that identifies the current platform.  This is used
  21.     mainly to distinguish platform-specific build directories and
  22.     platform-specific built distributions.  Typically includes the OS name
  23.     and version and the architecture (as supplied by 'os.uname()'),
  24.     although the exact information included depends on the OS; eg. for IRIX
  25.     the architecture isn't particularly important (IRIX only runs on SGI
  26.     hardware), but for Linux the kernel version isn't particularly
  27.     important.
  28.  
  29.     Examples of returned values:
  30.        linux-i586
  31.        linux-alpha (?)
  32.        solaris-2.6-sun4u
  33.        irix-5.3
  34.        irix64-6.2
  35.  
  36.     For non-POSIX platforms, currently just returns 'sys.platform'.
  37.     """
  38.     if os.name != 'posix' or not hasattr(os, 'uname'):
  39.         return sys.platform
  40.     
  41.     (osname, host, release, version, machine) = os.uname()
  42.     osname = string.lower(osname)
  43.     osname = string.replace(osname, '/', '')
  44.     machine = string.replace(machine, ' ', '_')
  45.     machine = string.replace(machine, '/', '-')
  46.     if osname[:5] == 'linux':
  47.         return '%s-%s' % (osname, machine)
  48.     elif osname[:5] == 'sunos':
  49.         if release[0] >= '5':
  50.             osname = 'solaris'
  51.             release = '%d.%s' % (int(release[0]) - 3, release[2:])
  52.         
  53.     elif osname[:4] == 'irix':
  54.         return '%s-%s' % (osname, release)
  55.     elif osname[:3] == 'aix':
  56.         return '%s-%s.%s' % (osname, version, release)
  57.     elif osname[:6] == 'cygwin':
  58.         osname = 'cygwin'
  59.         rel_re = re.compile('[\\d.]+')
  60.         m = rel_re.match(release)
  61.         if m:
  62.             release = m.group()
  63.         
  64.     elif osname[:6] == 'darwin':
  65.         get_config_vars = get_config_vars
  66.         import distutils.sysconfig
  67.         cfgvars = get_config_vars()
  68.         macver = os.environ.get('MACOSX_DEPLOYMENT_TARGET')
  69.         if not macver:
  70.             macver = cfgvars.get('MACOSX_DEPLOYMENT_TARGET')
  71.         
  72.         if not macver:
  73.             
  74.             try:
  75.                 f = open('/System/Library/CoreServices/SystemVersion.plist')
  76.             except IOError:
  77.                 pass
  78.  
  79.             m = re.search('<key>ProductUserVisibleVersion</key>\\s*' + '<string>(.*?)</string>', f.read())
  80.             f.close()
  81.             if m is not None:
  82.                 macver = '.'.join(m.group(1).split('.')[:2])
  83.             
  84.         
  85.         if macver:
  86.             get_config_vars = get_config_vars
  87.             import distutils.sysconfig
  88.             release = macver
  89.             osname = 'macosx'
  90.             platver = os.uname()[2]
  91.             osmajor = int(platver.split('.')[0])
  92.             if osmajor >= 8 and get_config_vars().get('UNIVERSALSDK', '').strip():
  93.                 machine = 'fat'
  94.             elif machine in ('PowerPC', 'Power_Macintosh'):
  95.                 machine = 'ppc'
  96.             
  97.         
  98.     
  99.     return '%s-%s-%s' % (osname, release, machine)
  100.  
  101.  
  102. def convert_path(pathname):
  103.     """Return 'pathname' as a name that will work on the native filesystem,
  104.     i.e. split it on '/' and put it back together again using the current
  105.     directory separator.  Needed because filenames in the setup script are
  106.     always supplied in Unix style, and have to be converted to the local
  107.     convention before we can actually use them in the filesystem.  Raises
  108.     ValueError on non-Unix-ish systems if 'pathname' either starts or
  109.     ends with a slash.
  110.     """
  111.     if os.sep == '/':
  112.         return pathname
  113.     
  114.     if not pathname:
  115.         return pathname
  116.     
  117.     if pathname[0] == '/':
  118.         raise ValueError, "path '%s' cannot be absolute" % pathname
  119.     
  120.     if pathname[-1] == '/':
  121.         raise ValueError, "path '%s' cannot end with '/'" % pathname
  122.     
  123.     paths = string.split(pathname, '/')
  124.     while '.' in paths:
  125.         paths.remove('.')
  126.     if not paths:
  127.         return os.curdir
  128.     
  129.     return apply(os.path.join, paths)
  130.  
  131.  
  132. def change_root(new_root, pathname):
  133.     '''Return \'pathname\' with \'new_root\' prepended.  If \'pathname\' is
  134.     relative, this is equivalent to "os.path.join(new_root,pathname)".
  135.     Otherwise, it requires making \'pathname\' relative and then joining the
  136.     two, which is tricky on DOS/Windows and Mac OS.
  137.     '''
  138.     if os.name == 'posix':
  139.         if not os.path.isabs(pathname):
  140.             return os.path.join(new_root, pathname)
  141.         else:
  142.             return os.path.join(new_root, pathname[1:])
  143.     elif os.name == 'nt':
  144.         (drive, path) = os.path.splitdrive(pathname)
  145.         if path[0] == '\\':
  146.             path = path[1:]
  147.         
  148.         return os.path.join(new_root, path)
  149.     elif os.name == 'os2':
  150.         (drive, path) = os.path.splitdrive(pathname)
  151.         if path[0] == os.sep:
  152.             path = path[1:]
  153.         
  154.         return os.path.join(new_root, path)
  155.     elif os.name == 'mac':
  156.         if not os.path.isabs(pathname):
  157.             return os.path.join(new_root, pathname)
  158.         else:
  159.             elements = string.split(pathname, ':', 1)
  160.             pathname = ':' + elements[1]
  161.             return os.path.join(new_root, pathname)
  162.     else:
  163.         raise DistutilsPlatformError, "nothing known about platform '%s'" % os.name
  164.  
  165. _environ_checked = 0
  166.  
  167. def check_environ():
  168.     """Ensure that 'os.environ' has all the environment variables we
  169.     guarantee that users can use in config files, command-line options,
  170.     etc.  Currently this includes:
  171.       HOME - user's home directory (Unix only)
  172.       PLAT - description of the current platform, including hardware
  173.              and OS (see 'get_platform()')
  174.     """
  175.     global _environ_checked
  176.     if _environ_checked:
  177.         return None
  178.     
  179.     if os.name == 'posix' and not os.environ.has_key('HOME'):
  180.         import pwd
  181.         os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
  182.     
  183.     if not os.environ.has_key('PLAT'):
  184.         os.environ['PLAT'] = get_platform()
  185.     
  186.     _environ_checked = 1
  187.  
  188.  
  189. def subst_vars(s, local_vars):
  190.     """Perform shell/Perl-style variable substitution on 'string'.  Every
  191.     occurrence of '$' followed by a name is considered a variable, and
  192.     variable is substituted by the value found in the 'local_vars'
  193.     dictionary, or in 'os.environ' if it's not in 'local_vars'.
  194.     'os.environ' is first checked/augmented to guarantee that it contains
  195.     certain values: see 'check_environ()'.  Raise ValueError for any
  196.     variables not found in either 'local_vars' or 'os.environ'.
  197.     """
  198.     check_environ()
  199.     
  200.     def _subst(match, local_vars = local_vars):
  201.         var_name = match.group(1)
  202.         if local_vars.has_key(var_name):
  203.             return str(local_vars[var_name])
  204.         else:
  205.             return os.environ[var_name]
  206.  
  207.     
  208.     try:
  209.         return re.sub('\\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s)
  210.     except KeyError:
  211.         var = None
  212.         raise ValueError, "invalid variable '$%s'" % var
  213.  
  214.  
  215.  
  216. def grok_environment_error(exc, prefix = 'error: '):
  217.     """Generate a useful error message from an EnvironmentError (IOError or
  218.     OSError) exception object.  Handles Python 1.5.1 and 1.5.2 styles, and
  219.     does what it can to deal with exception objects that don't have a
  220.     filename (which happens when the error is due to a two-file operation,
  221.     such as 'rename()' or 'link()'.  Returns the error message as a string
  222.     prefixed with 'prefix'.
  223.     """
  224.     if hasattr(exc, 'filename') and hasattr(exc, 'strerror'):
  225.         if exc.filename:
  226.             error = prefix + '%s: %s' % (exc.filename, exc.strerror)
  227.         else:
  228.             error = prefix + '%s' % exc.strerror
  229.     else:
  230.         error = prefix + str(exc[-1])
  231.     return error
  232.  
  233. _wordchars_re = None
  234. _squote_re = None
  235. _dquote_re = None
  236.  
  237. def _init_regex():
  238.     global _wordchars_re, _squote_re, _dquote_re
  239.     _wordchars_re = re.compile('[^\\\\\\\'\\"%s ]*' % string.whitespace)
  240.     _squote_re = re.compile("'(?:[^'\\\\]|\\\\.)*'")
  241.     _dquote_re = re.compile('"(?:[^"\\\\]|\\\\.)*"')
  242.  
  243.  
  244. def split_quoted(s):
  245.     '''Split a string up according to Unix shell-like rules for quotes and
  246.     backslashes.  In short: words are delimited by spaces, as long as those
  247.     spaces are not escaped by a backslash, or inside a quoted string.
  248.     Single and double quotes are equivalent, and the quote characters can
  249.     be backslash-escaped.  The backslash is stripped from any two-character
  250.     escape sequence, leaving only the escaped character.  The quote
  251.     characters are stripped from any quoted string.  Returns a list of
  252.     words.
  253.     '''
  254.     if _wordchars_re is None:
  255.         _init_regex()
  256.     
  257.     s = string.strip(s)
  258.     words = []
  259.     pos = 0
  260.     while s:
  261.         m = _wordchars_re.match(s, pos)
  262.         end = m.end()
  263.         if end == len(s):
  264.             words.append(s[:end])
  265.             break
  266.         
  267.         if s[end] in string.whitespace:
  268.             words.append(s[:end])
  269.             s = string.lstrip(s[end:])
  270.             pos = 0
  271.         elif s[end] == '\\':
  272.             s = s[:end] + s[end + 1:]
  273.             pos = end + 1
  274.         elif s[end] == "'":
  275.             m = _squote_re.match(s, end)
  276.         elif s[end] == '"':
  277.             m = _dquote_re.match(s, end)
  278.         else:
  279.             raise RuntimeError, "this can't happen (bad char '%c')" % s[end]
  280.         if m is None:
  281.             raise ValueError, 'bad string (mismatched %s quotes?)' % s[end]
  282.         
  283.         (beg, end) = m.span()
  284.         s = s[:beg] + s[beg + 1:end - 1] + s[end:]
  285.         pos = m.end() - 2
  286.         if pos >= len(s):
  287.             words.append(s)
  288.             break
  289.             continue
  290.     return words
  291.  
  292.  
  293. def execute(func, args, msg = None, verbose = 0, dry_run = 0):
  294.     '''Perform some action that affects the outside world (eg.  by
  295.     writing to the filesystem).  Such actions are special because they
  296.     are disabled by the \'dry_run\' flag.  This method takes care of all
  297.     that bureaucracy for you; all you have to do is supply the
  298.     function to call and an argument tuple for it (to embody the
  299.     "external action" being performed), and an optional message to
  300.     print.
  301.     '''
  302.     if msg is None:
  303.         msg = '%s%r' % (func.__name__, args)
  304.         if msg[-2:] == ',)':
  305.             msg = msg[0:-2] + ')'
  306.         
  307.     
  308.     log.info(msg)
  309.     if not dry_run:
  310.         apply(func, args)
  311.     
  312.  
  313.  
  314. def strtobool(val):
  315.     """Convert a string representation of truth to true (1) or false (0).
  316.  
  317.     True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
  318.     are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if
  319.     'val' is anything else.
  320.     """
  321.     val = string.lower(val)
  322.     if val in ('y', 'yes', 't', 'true', 'on', '1'):
  323.         return 1
  324.     elif val in ('n', 'no', 'f', 'false', 'off', '0'):
  325.         return 0
  326.     else:
  327.         raise ValueError, 'invalid truth value %r' % (val,)
  328.  
  329.  
  330. def byte_compile(py_files, optimize = 0, force = 0, prefix = None, base_dir = None, verbose = 1, dry_run = 0, direct = None):
  331.     '''Byte-compile a collection of Python source files to either .pyc
  332.     or .pyo files in the same directory.  \'py_files\' is a list of files
  333.     to compile; any files that don\'t end in ".py" are silently skipped.
  334.     \'optimize\' must be one of the following:
  335.       0 - don\'t optimize (generate .pyc)
  336.       1 - normal optimization (like "python -O")
  337.       2 - extra optimization (like "python -OO")
  338.     If \'force\' is true, all files are recompiled regardless of
  339.     timestamps.
  340.  
  341.     The source filename encoded in each bytecode file defaults to the
  342.     filenames listed in \'py_files\'; you can modify these with \'prefix\' and
  343.     \'basedir\'.  \'prefix\' is a string that will be stripped off of each
  344.     source filename, and \'base_dir\' is a directory name that will be
  345.     prepended (after \'prefix\' is stripped).  You can supply either or both
  346.     (or neither) of \'prefix\' and \'base_dir\', as you wish.
  347.  
  348.     If \'dry_run\' is true, doesn\'t actually do anything that would
  349.     affect the filesystem.
  350.  
  351.     Byte-compilation is either done directly in this interpreter process
  352.     with the standard py_compile module, or indirectly by writing a
  353.     temporary script and executing it.  Normally, you should let
  354.     \'byte_compile()\' figure out to use direct compilation or not (see
  355.     the source for details).  The \'direct\' flag is used by the script
  356.     generated in indirect mode; unless you know what you\'re doing, leave
  357.     it set to None.
  358.     '''
  359.     if direct is None:
  360.         if __debug__:
  361.             pass
  362.         direct = optimize == 0
  363.     
  364.     if not direct:
  365.         
  366.         try:
  367.             mkstemp = mkstemp
  368.             import tempfile
  369.             (script_fd, script_name) = mkstemp('.py')
  370.         except ImportError:
  371.             mktemp = mktemp
  372.             import tempfile
  373.             script_fd = None
  374.             script_name = mktemp('.py')
  375.  
  376.         log.info("writing byte-compilation script '%s'", script_name)
  377.         if not dry_run:
  378.             if script_fd is not None:
  379.                 script = os.fdopen(script_fd, 'w')
  380.             else:
  381.                 script = open(script_name, 'w')
  382.             script.write('from distutils.util import byte_compile\nfiles = [\n')
  383.             script.write(string.join(map(repr, py_files), ',\n') + ']\n')
  384.             script.write('\nbyte_compile(files, optimize=%r, force=%r,\n             prefix=%r, base_dir=%r,\n             verbose=%r, dry_run=0,\n             direct=1)\n' % (optimize, force, prefix, base_dir, verbose))
  385.             script.close()
  386.         
  387.         cmd = [
  388.             sys.executable,
  389.             script_name]
  390.         if optimize == 1:
  391.             cmd.insert(1, '-O')
  392.         elif optimize == 2:
  393.             cmd.insert(1, '-OO')
  394.         
  395.         spawn(cmd, dry_run = dry_run)
  396.         execute(os.remove, (script_name,), 'removing %s' % script_name, dry_run = dry_run)
  397.     else:
  398.         compile = compile
  399.         import py_compile
  400.         for file in py_files:
  401.             if file[-3:] != '.py':
  402.                 continue
  403.             
  404.             if not __debug__ or 'c':
  405.                 pass
  406.             cfile = file + 'o'
  407.             dfile = file
  408.             if prefix:
  409.                 if file[:len(prefix)] != prefix:
  410.                     raise ValueError, "invalid prefix: filename %r doesn't start with %r" % (file, prefix)
  411.                 
  412.                 dfile = dfile[len(prefix):]
  413.             
  414.             if base_dir:
  415.                 dfile = os.path.join(base_dir, dfile)
  416.             
  417.             cfile_base = os.path.basename(cfile)
  418.             if direct:
  419.                 if force or newer(file, cfile):
  420.                     log.info('byte-compiling %s to %s', file, cfile_base)
  421.                     if not dry_run:
  422.                         compile(file, cfile, dfile)
  423.                     
  424.                 else:
  425.                     log.debug('skipping byte-compilation of %s to %s', file, cfile_base)
  426.             newer(file, cfile)
  427.         
  428.  
  429.  
  430. def rfc822_escape(header):
  431.     '''Return a version of the string escaped for inclusion in an
  432.     RFC-822 header, by ensuring there are 8 spaces space after each newline.
  433.     '''
  434.     lines = string.split(header, '\n')
  435.     lines = map(string.strip, lines)
  436.     header = string.join(lines, '\n' + 8 * ' ')
  437.     return header
  438.  
  439.